package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @description：订单状态定时处理任务类
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrdersMapper ordersMapper;

    /**
     * 15分钟未支付订单任务处理（超时未支付订单）
     */
    @Scheduled(cron = "0 0/1 * * * ?") // 每分钟执行一次
    public void timeoutOrderTask() {
        log.info("超时未支付订单检测定时任务执行...");

        //1、查询下单时间 小于 当前时间-15分钟 并且状态为【待支付】的订单
        List<Orders> ordersList = ordersMapper.queryByStatusAndOrderTime(Orders.PENDING_PAYMENT, LocalDateTime.now().plusMinutes(-15));

        //2、循环或批量修改订单状态（状态、取消时间，取消原因）
        if (ObjectUtils.isNotEmpty(ordersList)) {
            List<Long> ids = ordersList.stream().map(o -> o.getId()).collect(Collectors.toList());
            Orders order = Orders.builder().status(Orders.CANCELLED).cancelTime(LocalDateTime.now()).cancelReason("订单超时").build();
            ordersMapper.batchUpdate(ids, order);
        }
    }

    @Scheduled(cron = "0/30 * * * * ?")
    public void deliveryOrderTask() {
        log.info("前一日未完成订单检测定时任务执行...");

        // 查询下单时间小于（当前时间-60） 并且状态为待支付的订单
        final LocalDateTime dateTime = LocalDateTime.now().plusMinutes(-60);
        List<Orders> ordersList = ordersMapper.queryByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS, dateTime);

        // 批量修改订单状态
        if (ObjectUtils.isNotEmpty(ordersList)){
            final List<Long> ids = ordersList.stream().map(o -> o.getId()).collect(Collectors.toList());
            final Orders order = Orders.builder().status(Orders.COMPLETED).deliveryTime(LocalDateTime.now()).build();
            ordersMapper.batchUpdate(ids,order);
        }
    }
}
